package com.sxj.corejava.code13_线程;

/**
 * @author 石小俊
 */
public class Test07_线程间的通信 {
    public static void main(String[] args) {
        Object obj = new Object();
        WaitThread t1 = new WaitThread(obj,"线程1");
        WaitThreadTwo t2 = new WaitThreadTwo(obj,"线程2");
        t1.start();
        t2.start();

//        Object obj2 = new Object();
//        NotifyThread notifyThread = new NotifyThread(obj,"notify线程");
//        NotifyThread notifyThread = new NotifyThread(obj2,"notify线程");
//        notifyThread.start();

        NotifyAllThread notifyAllThread = new NotifyAllThread(obj,"notifyAll线程");
        notifyAllThread.start();
    }
}

class WaitThread extends Thread{
    private Object obj;
    private String name;

    public WaitThread(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj){
//            System.out.println(name+"拿到锁,进入线程同步语句块");
            System.out.println(name+"释放锁,即将进入等待池");
            try {
                // 等待方法可以设置等待时间,到达指定毫秒后自动唤醒
//                obj.wait(3000);
                // 也可以不设置等待时间,无限等待，直到被唤醒
                obj.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(name+"执行完成");
    }
}

class WaitThreadTwo extends Thread{
    private Object obj;
    private String name;

    public WaitThreadTwo(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj){
            System.out.println(name+"释放锁,即将进入等待池");
            try {
                obj.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(name+"执行完成");
    }
}

class NotifyThread extends Thread{
    private Object obj;
    private String name;

    public NotifyThread(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj){
            obj.notify();
            System.out.println("已经随机唤醒了等待池中某一个线程");
        }
    }
}

class NotifyAllThread extends Thread{
    private Object obj;
    private String name;

    public NotifyAllThread(Object obj, String name) {
        this.obj = obj;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (obj){
            obj.notifyAll();
            System.out.println("已经唤醒了等待池中所有的线程");
        }
    }
}